/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.mywork.potentialcustomer.web;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.knet.sp.ncrm.common.persistence.AjaxMessage;
import cn.knet.sp.ncrm.common.persistence.Page;
import cn.knet.sp.ncrm.common.service.ServiceException;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.common.web.BaseController;
import cn.knet.sp.ncrm.common.web.bind.annotation.FormModel;
import cn.knet.sp.ncrm.modules.customer.aftersalesservice.entity.PotentialAfterSalesService;
import cn.knet.sp.ncrm.modules.customer.appointment.entity.PotentialAppointmentInfo;
import cn.knet.sp.ncrm.modules.customer.importsupport.ImportService;
import cn.knet.sp.ncrm.modules.customer.importsupport.ImportUtil;
import cn.knet.sp.ncrm.modules.customer.importsupport.ImportVO;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.entity.PotentialCustomer;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.service.PotentialCustomerService;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.vo.PotentialCustomerVo;
import cn.knet.sp.ncrm.modules.customer.visitrecord.entity.VisitRecord;
import cn.knet.sp.ncrm.modules.customer.potentialgroup.entity.PotentialGroup;
import cn.knet.sp.ncrm.modules.mywork.potentialcustomer.service.MyPotentialCustomerService;
import cn.knet.sp.ncrm.modules.customer.potentialgroup.service.PotentialGroupService;
import cn.knet.sp.ncrm.modules.sys.customerstatus.service.CustomerStatusService;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;
import cn.knet.sp.ncrm.modules.sys.user.service.SystemService;
import cn.knet.sp.ncrm.modules.sys.utils.CustomerUtils;
import cn.knet.sp.ncrm.modules.sys.utils.UserUtils;

/**
 * 我的潜在客户 Controller
 *
 * @author 冯亚鹏
 * @version 2015-08-24
 */
@Controller
@RequestMapping(value = "${adminPath}/mywork/potentialCustomer")
public class MyPotentialCustomerController extends BaseController {

	@Autowired
	private PotentialCustomerService potentialCustomerService;

	@Autowired
	private ImportService importService;

	@Autowired
	private PotentialGroupService potentialGroupService;

	@Resource
	private SystemService systemService;

	@Resource
	private MyPotentialCustomerService myPotentialCustomerService;

	@Resource
	private CustomerStatusService customerStatusService;

	@ModelAttribute
	public PotentialCustomer get(@RequestParam(required = false) String id, @RequestParam(required = false) String potentialCustomerId) {
		PotentialCustomer entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = new PotentialCustomer();
			entity.setId(id);
			entity.setExecutorId(UserUtils.getUser().getId());
			entity = potentialCustomerService.get(entity);

		}
		if (entity == null && StringUtils.isNotBlank(potentialCustomerId)) {
			entity = new PotentialCustomer();
			entity.setId(potentialCustomerId);
			entity.setExecutorId(UserUtils.getUser().getId());
			entity = potentialCustomerService.get(entity);

		}
		if (entity == null) {
			entity = new PotentialCustomer();
		}
		return entity;
	}

	/**
	 * 我的列表
	 *
	 * @author fengyapeng
	 * @since 2015 /09/06 14:51:17 string
	 */
	@RequiresPermissions("mywork:potentialCustomer:view")
	@RequestMapping(value = {"mylist"})
	public String mylist(PotentialCustomer potentialCustomer, Model model) {
		return "modules/mywork/potentialcustomer/myList";
	}



	private ArrayList<String> getUnableCustomerStatusIds(){
		ArrayList customersStatusIds = new ArrayList<String>();
		String statusIdWu = CustomerUtils.getStatusIdByName("无意向");
		String statusIdUnable = CustomerUtils.getStatusIdByName("无效数据");
		if (statusIdWu != null) {
			customersStatusIds.add(statusIdWu);
		}
		if (statusIdUnable != null) {
			customersStatusIds.add(statusIdUnable);
		}
		return customersStatusIds;
	}
	/**
	 * 分配给我的列表
	 *
	 * @author fengyapeng
	 * @since 2015 /09/06 14:51:20 string
	 */
	@RequiresPermissions("mywork:potentialCustomer:view")
	@RequestMapping(value = "distlist")
	public String distlist(PotentialCustomer potentialCustomer, Model model) {
		ArrayList<String> customersStatusIds = getUnableCustomerStatusIds();
		ArrayList<String> executorIds = new ArrayList();
		model.addAttribute("oneKeyCloseNum", 0);// 一键结束数量为0
		if (customersStatusIds.size() > 0) {
			User currentUser = UserUtils.getUser();
			executorIds.add(currentUser.getId());// 当前的执行人
			Integer oneKeyCloseNum = 0;
			oneKeyCloseNum = this.potentialCustomerService.countByCustomerStatusIds(executorIds, customersStatusIds);
			model.addAttribute("oneKeyCloseNum", oneKeyCloseNum != null ? oneKeyCloseNum : 0);
			if ("2".equals(currentUser.getUserType())) {// 用户类型等于2（部门主管）
				String officeId = currentUser.getOffice().getId();
				List<User> allOfficeUsers = systemService.getAllUserByOfficeId(officeId);// 查询部门下的所有的人员
				executorIds.clear();
				for (User user : allOfficeUsers) {
					executorIds.add(user.getId());
				}
				Integer oneKeyAllCloseNum = 0;
				oneKeyAllCloseNum = this.potentialCustomerService.countByCustomerStatusIds(executorIds, customersStatusIds);
				model.addAttribute("oneKeyCloseAllNum", oneKeyAllCloseNum != null ? oneKeyAllCloseNum : 0);
			}
		}
		return "modules/mywork/potentialcustomer/distList";
	}


	/**
	 * TODO 暂时未测试，按照目前正常的逻辑无法产生一键结束的数据
	 * 一键结束属于自己的客户
	 *
	 * @author fengyapeng
	 * @since 2015 /09/11 15:22:47
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "oneKeyClose")
	@ResponseBody
	public AjaxMessage oneKeyClose() {
		try {
			ArrayList<String> customersStatusIds = getUnableCustomerStatusIds();
			ArrayList<String> executorIds = new ArrayList();
			if (customersStatusIds.size() > 0) {// 有这两个状态，继续一键结束的逻辑
				String currentUserId = UserUtils.getUser().getId();
				executorIds.add(currentUserId);
				VisitRecord visitRecord = new VisitRecord();
				visitRecord.setVisitResult("SUCCESS");
				visitRecord.setOperationType("END");
				visitRecord.setVisitRecord(UserUtils.getUser().getName()+" 一键结束");
				List<PotentialCustomer> oneClosePttCustomers = this.potentialCustomerService.findListByCustomerStatusIds(executorIds, customersStatusIds);
				for (PotentialCustomer pttCus : oneClosePttCustomers){
					visitRecord.setPotentialCustomerId(pttCus.getId());
					visitRecord.setCustomerStatusId(customersStatusIds.get(0));// 将客户状态改为无意向
					myPotentialCustomerService.visitRecordEnd(pttCus,visitRecord);
				}
			}
			return AjaxMessage.success("一键结束成功");
		} catch (Exception e) {
			logger.error("一键结束失败",e);
			return AjaxMessage.error("一键结束失败");
		}
	}

	/**
	 * TODO 暂时未测试，按照目前正常的逻辑无法产生一键结束的数据
	 * 一键结束自己以及下属所有人的无效&无意向客户
	 *
	 * @author fengyapeng
	 * @since 2015 /09/11 15:23:44
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "oneKeyCloseAll")
	@ResponseBody
	public AjaxMessage oneKeyCloseAll() {
		try {
			ArrayList<String> customersStatusIds = getUnableCustomerStatusIds();
			ArrayList<String> executorIds = new ArrayList();
			User currentUser = UserUtils.getUser();

			if (customersStatusIds.size() > 0) {// 有这两个状态，继续一键结束的逻辑
				String officeId = currentUser.getOffice().getId();
				List<User> allOfficeUsers = systemService.getAllUserByOfficeId(officeId);// 查询部门下的所有的人员
				for (User user : allOfficeUsers) {
					executorIds.add(user.getId());
				}
				VisitRecord visitRecord = new VisitRecord();
				visitRecord.setVisitResult("SUCCESS");
				visitRecord.setOperationType("END");
				visitRecord.setVisitRecord(UserUtils.getUser().getName()+" 一键结束");
				List<PotentialCustomer> oneClosePttCustomers = this.potentialCustomerService.findListByCustomerStatusIds(executorIds, customersStatusIds);
				for (PotentialCustomer pttCus : oneClosePttCustomers){
					visitRecord.setPotentialCustomerId(pttCus.getId());
					visitRecord.setCustomerStatusId(customersStatusIds.get(0));// 将客户状态改为无意向
					myPotentialCustomerService.visitRecordEnd(pttCus,visitRecord);
				}
			}
			return AjaxMessage.success("一键结束所有数据成功");
		} catch (Exception e) {
			logger.error("一键结束所有数据失败");
			return AjaxMessage.error("一键结束所有数据失败");
		}
	}


	/**
	 * 分配数据获取
	 *
	 * @param potentialCustomer the potential customer
	 * @param model             the model
	 * @param request           the request
	 * @param response          the response
	 * @return the object
	 * @author fengyapeng
	 * @since 2015 /09/06 14:51:22
	 */
	@RequiresPermissions("mywork:potentialCustomer:view")
	@RequestMapping(value = "listDistData")
	@ResponseBody
	public Object listDistData(PotentialCustomer potentialCustomer, Model model, HttpServletRequest request, HttpServletResponse response) {
		//判断数据是否第一次加载，第一次加载默认查询未分配状态的数据
		if (!request.getParameterMap().containsKey("distStatus")) {
			potentialCustomer.setDistStatus("DISTED");
		}
		potentialCustomer.setRecordVisibilityRule("public");
		User user = UserUtils.getUser();
		potentialCustomer.setExecutorId(user.getId());
		Page page = new Page<PotentialCustomer>(request, response);
		page.setOrderBy("a.last_updated desc");
		return potentialCustomerService.findMyPage(page, potentialCustomer);

	}


	/**
	 * 个人数据获取
	 *
	 * @param potentialCustomer the potential customer
	 * @param model             the model
	 * @param request           the request
	 * @param response          the response
	 * @return the object
	 * @author fengyapeng
	 * @since 2015 /09/06 14:51:27
	 */
	@RequiresPermissions("mywork:potentialCustomer:view")
	@RequestMapping(value = "listMyData")
	@ResponseBody
	public Object listMyData(PotentialCustomer potentialCustomer, Model model, HttpServletRequest request, HttpServletResponse response) {
		//判断数据是否第一次加载，第一次加载默认查询未分配状态的数据

		potentialCustomer.setVisibilityUserId(UserUtils.getUser().getId());
		potentialCustomer.setRecordVisibilityRule("private");

		Page page = new Page<PotentialCustomer>(request, response);
		page.setOrderBy("a.last_updated desc");
		return potentialCustomerService.findMyPage(page, potentialCustomer);

	}

	/**
	 * 详细页面
	 *
	 * @author fengyapeng
	 * @since 2015 /09/06 14:51:30 string
	 */
	/*@RequiresPermissions("mywork:potentialCustomer:detail")
	@RequestMapping(value = "detail")
	public String detail(PotentialCustomer potentialCustomer, Model model) {
		if (potentialCustomer.getIsNewRecord()) {
			return "modules/mywork/potentialcustomer/detailNotFound";
		}
		//详细页面
		potentialCustomer.setExecutorId(UserUtils.getUser().getId());
		PotentialCustomerVo potentialCustomerVo = this.potentialCustomerService.getDetail(potentialCustomer);
		if (potentialCustomerVo == null) {
			return "modules/mywork/potentialcustomer/detailNotFound";
		}
		model.addAttribute("ableCall",true);// 能够打电话
		model.addAttribute("vo", potentialCustomerVo);
		return "modules/mywork/potentialcustomer/detail";
	}*/

	/**
	 * 跳转详细页面
	 *
	 * @author Gehaiyang
	 * @date 2015年9月10日 下午1:17:42
	 */
	@RequiresPermissions("mywork:potentialCustomer:detail")
	@RequestMapping(value = "detail")
	public String detail(@ModelAttribute PotentialCustomer potentialCustomer, Model model) {
			if (potentialCustomer.getIsNewRecord()) {
			return "modules/mywork/potentialcustomer/detailNotFound";
		}
		potentialCustomerService.modifyNoReadNum(potentialCustomer);
		model.addAttribute("id", potentialCustomer.getId());
		model.addAttribute("flag", 1);
		return "modules/mywork/potentialcustomer/detail";
	}

	/**
	 * 跳转基本信息页面
	 *
	 * @author Gehaiyang
	 * @date 2015年9月10日 下午1:17:59
	 */
	@RequiresPermissions("mywork:potentialCustomer:detail")
	@RequestMapping(value = "detailBasicInfo")
	public String detailBasicInfo(PotentialCustomerVo potentialCustomerVo, Model model) {
		PotentialCustomerVo vo = potentialCustomerService.getDetail(potentialCustomerVo);
		vo.setFlag(potentialCustomerVo.getFlag());
		model.addAttribute("vo", vo);
		model.addAttribute("ableCall", true);// 能够打电话
		return "modules/customer/potentialcustomer/detail/detailBasicInfo";
	}

	/**
	 * 修改基本信息
	 *
	 * @author Gehaiyang
	 * @date 2015年9月10日 下午1:18:25
	 */
	@RequiresPermissions("mywork:potentialCustomer:detail")
	@RequestMapping(value = "detailBasicForm")
	public String detailBasicForm(PotentialCustomerVo potentialCustomerVo, Model model) {
		PotentialCustomerVo vo = potentialCustomerService.getDetail(potentialCustomerVo);
		vo.setFlag(potentialCustomerVo.getFlag());
		model.addAttribute("vo", vo);
		return "modules/customer/potentialcustomer/detail/detailBasicForm";
	}

	/**
	 * 再次分配
	 *
	 * @author fengyapeng
	 * @since 2015 /09/06 14:51:35 ajax message
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "reDist")
	@ResponseBody
	public AjaxMessage reDist(String[] ids, String[] userIds) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		try {
			if (ids.length == 0) {
				ajaxMessage.makeError("请选择需要分配的数据");
				return ajaxMessage;
			}
			if (userIds.length == 0) {
				ajaxMessage.makeError("请选择需要分配的人员");
				return ajaxMessage;
			}
			potentialCustomerService.distData(ids, userIds);
			ajaxMessage.setMessage("数据分配成功");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("分配数据出现问题，请稍后再试");
		}
		return ajaxMessage;
	}

	/**
	 * 分配
	 *
	 * @param potentialCustomer  the potential customer
	 * @param model              the model
	 * @param redirectAttributes the redirect attributes
	 * @return the string
	 * @author fengyapeng
	 * @since 2015 /09/06 14:51:47
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "reDistIndex")
	public String reDistIndex(PotentialCustomer potentialCustomer, Model model, RedirectAttributes redirectAttributes) {
		return "modules/mywork/potentialcustomer/reDistIndex";
	}


	/**
	 * 分配的用户查询
	 *
	 * @param user     the user
	 * @param request  the request
	 * @param response the response
	 * @return the page
	 * @author fengyapeng
	 * @since 2015 /09/06 14:51:57
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "reDistListUser")
	@ResponseBody
	public Page<User> reDistUser(User user, HttpServletRequest request, HttpServletResponse response) {
		return systemService.findUser(new Page<User>(request, response), user);
	}


	/**
	 * 合并数据
	 *
	 * @param potentialCustomer the potential customer
	 * @return the ajax message
	 * @author 冯亚鹏
	 * @date 2015年9月1日 下午3:38:55
	 * @since 2015 /09/06 14:51:52 ajax message
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "merge")
	@ResponseBody
	public AjaxMessage merge(PotentialCustomer potentialCustomer) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		try {
			if (ArrayUtils.isEmpty(potentialCustomer.getIds())) {
				ajaxMessage.makeError("请选择需要合并的数据");
			} else if (StringUtils.isBlank(potentialCustomer.getId())) {
				ajaxMessage.makeError("请选择主数据");
			} else {
				potentialCustomerService.mergerData(potentialCustomer);
				ajaxMessage.setMessage("合并成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("合并出现异常，请稍后重试");
		}
		return ajaxMessage;
	}


	/**
	 * 分组
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "group")
	@ResponseBody
	public AjaxMessage group(String groupId, String[] ids) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		try {
			if (ids.length == 0) {
				ajaxMessage.makeError("请选择需要分组的数据");
				return ajaxMessage;
			}
			if (StringUtils.isBlank(groupId)) {
				ajaxMessage.makeError("请选择分组");
				return ajaxMessage;
			}
			potentialCustomerService.updateGroup(ids, groupId);
			ajaxMessage.setMessage("数据分组成功");
		} catch (ServiceException se) {
			ajaxMessage.makeError(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("数据分组出现问题，请稍后再试");
		}
		return ajaxMessage;
	}


	/**
	 * 创建跟踪回访记录
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "visitRecordCreate")
	@ResponseBody
	public AjaxMessage visitRecordCreate( PotentialCustomer potentialCustomer, String targetProducts,
										 @FormModel("visitRecord") VisitRecord myVisitRecord,
										 @FormModel("appointment") PotentialAppointmentInfo potentialAppointmentInfo) {
		if (potentialCustomer.getIsNewRecord()) {
			return AjaxMessage.error("你无法访问该客户");
		}
		try {
			if (myVisitRecord != null) {
				myVisitRecord.setTargetProducts(targetProducts);
			}
			this.myPotentialCustomerService.visitRecordCreate(potentialCustomer, myVisitRecord, potentialAppointmentInfo);
			return AjaxMessage.success("创建销售跟踪记录成功");
		} catch (Exception e) {
			logger.error("创建跟踪回访记录失败", e);
			return AjaxMessage.error("创建销售跟踪记录失败");
		}
	}


	/**
	 * 创建跟踪回访记录，并记录成单信息,成单不记录 预约信息
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "visitRecordDone")
	@ResponseBody
	public AjaxMessage visitRecordDone(PotentialCustomer potentialCustomer, String targetProducts,
									   @FormModel("visitRecord") VisitRecord visitRecord,
									   @FormModel("salesService") PotentialAfterSalesService potentialAfterSalesService) {
		if (potentialCustomer.getIsNewRecord()) {
			return AjaxMessage.error("你无法访问该客户");
		}
		try {
			if (visitRecord != null) {
				visitRecord.setTargetProducts(targetProducts);
			}
			if (potentialAfterSalesService != null) {
				potentialAfterSalesService.setTargetproducts(targetProducts);
			}
			this.myPotentialCustomerService.visitRecordDone(potentialCustomer, visitRecord, potentialAfterSalesService);
			return AjaxMessage.success("创建成单记录成功");
		} catch (Exception e) {
			logger.error("创建跟踪回访记录失败", e);
			return AjaxMessage.error("创建成单记录失败");
		}
	}


	/**
	 * 创建跟踪回访记录，无意向或者无效数据的成单,不记录预约信息
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "visitRecordEnd")
	@ResponseBody
	public AjaxMessage visitRecordEnd(PotentialCustomer potentialCustomer, String targetProducts,
									  @FormModel("visitRecord") VisitRecord visitRecord) {
		if (potentialCustomer.getIsNewRecord()) {
			return AjaxMessage.error("你无法访问该客户");
		}
		try {
			if (visitRecord != null) {
				visitRecord.setTargetProducts(targetProducts);
			}
			this.myPotentialCustomerService.visitRecordEnd(potentialCustomer, visitRecord);
			return AjaxMessage.success("销售跟踪结束成功");
		} catch (Exception e) {
			logger.error("销售跟踪结束失败", e);
			return AjaxMessage.error("销售跟踪结束失败");
		}
	}





	/*----------------------------导入部分代码 start---------------------------------*/


	/**
	 * 添加潜在客户表单
	 *
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequiresPermissions("mywork:potentialCustomer:view")
	@RequestMapping(value = "import/form")
	public String importForm(ImportVO vo, Model model) {
		int userWeight = 40;
		String userFlag = UserUtils.getUser().getUserType();

		if ("1".equals(userFlag)) {
			userWeight = 90;
		}else if ("2".equals(userFlag)){
			userWeight = 60;
		}

		model.addAttribute("customer", vo);
		model.addAttribute("userWeight", userWeight);
		return "modules/mywork/potentialcustomer/potentialCustomerImportForm";
	}

	/**
	 * 保存潜在客户表单
	 *
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "import/save")
	public String importSave(ImportVO vo, Model model, RedirectAttributes redirectAttributes) throws Exception {
		/*if (!beanValidator(model, vo)) {
			model.addAttribute("vo", vo);
			return "modules/mywork/potentialcustomer/potentialCustomerImportForm";
		}*/
		boolean flag = true;
		String errorMsg = "添加成功";

		//根据用户角色，判断是否合并
		List<ImportVO> voList = new ArrayList<ImportVO>();
		if (StringUtils.isBlank(vo.getWeight() + "")) {
			vo.setWeight(0);//权重
		}
		vo.setVersion(Long.parseLong("0"));//版本
		vo.setSource("系统添加");
		vo.setDateCreated(new Date());//创建时间
		vo.setLastUpdated(new Date());//最后更新时间
		vo.setDistStatus("UNDISTED");//分配状态
		vo.setMergerNum(0);//合并数量
		vo.setMobileOrPc("pc");//设备来源
		vo.setNoReadMergerNum(0);//未读合并数量
		vo.setVisitNum(0);//回访次数
		vo.setRecordVisibilityRule("private");//公有私有
		vo.setVisibilityUserId(UserUtils.getUser().getId());//持有人ID
		//仅个人导入需要初始化执行人ID
		vo.setExecutorId(UserUtils.getUser().getId());//执行人ID
		vo.setDelFlag("0");//删除标识

		voList.add(vo);

		int userWeight = 40;
		String userFlag = UserUtils.getUser().getUserType();

		if ("1".equals(userFlag)) {
			userWeight = 90;
		} else if ("2".equals(userFlag)) {
			userWeight = 60;
		}

		int successNum = voList.size();
		int mergerNum = 0;
		try {
			mergerNum = importService.save(voList, userWeight, false, "ADD");
		} catch (Exception e) {
			flag = false;
			errorMsg = "请检测导入的客户字段是否正确或者联系管理员";
			//e.printStackTrace();
		}

		model.addAttribute("successNum", successNum);
		model.addAttribute("mergerNum", mergerNum);
		model.addAttribute("flag", flag);
		model.addAttribute("errorMsg", errorMsg);

		return "modules/mywork/potentialcustomer/potentialCustomerImportResult";
	}


	/**
	 * 下载导入模板
	 *
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequiresPermissions("mywork:potentialCustomer:view")
	@RequestMapping(value = "import/template")
	public ResponseEntity<byte[]> importTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {

		File templateFile = new File(
				request.getSession().getServletContext().getRealPath("/static/templates/customer-of-import-templates.xlsx"));

		HttpHeaders headers = new HttpHeaders();
		//获取User-Agent
		String agent = request.getHeader("User-Agent");
		if (org.apache.commons.lang3.StringUtils.isNotBlank(agent) && agent.toLowerCase().contains("linux")) {
			//解决Linux系统浏览器乱码
			headers.setContentDispositionFormData("attachment", new String("客户基本信息导入模板.xlsx".getBytes("UTF-8"), "ISO8859-1"));
		} else {
			//解决Windows系统浏览器乱码
			headers.setContentDispositionFormData("attachment", new String("客户基本信息导入模板.xlsx".getBytes("GBK"), "ISO8859-1"));
		}
		//导出office2010文件，后缀格式.xlsx
		headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(templateFile), headers, HttpStatus.CREATED);

	}

	/**
	 * 导入用户数据
	 *
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequiresPermissions("mywork:potentialCustomer:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, String realGroupId, RedirectAttributes redirectAttributes, Model model) throws Exception {
		int successNum = 0;
		int mergerNum = 0;
		int maxsize = 8 * 1024 * 1024;//8M
		int maxRowNum = 10000;//1万条数据
		boolean flag = true;
		String errorMsg = "导入客户基本信息出现错误,请下载校验后的文件进行查看";

		if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equalsIgnoreCase(file.getContentType())
			|| "application/wps-office.xlsx".equalsIgnoreCase(file.getContentType())) {

			if (file.getSize() <= maxsize) {

				XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file.getInputStream());
				// Read the Sheet
				XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
				long begin = System.currentTimeMillis();
				int lastRowNum = xssfSheet.getLastRowNum();

				if (lastRowNum - 2 <= maxRowNum) {
					// Read the Row
					for (int rowNum = 3; rowNum <= lastRowNum; rowNum++) {
						XSSFRow xssfRow = xssfSheet.getRow(rowNum);

						if (null == xssfRow) {
							xssfRow = xssfSheet.createRow(rowNum);
							ImportUtil.setStyle(xssfWorkbook, xssfRow);
							flag = false;
							continue;
						} else {
							ImportUtil.setRowDefaultStyle(xssfWorkbook, xssfRow);
						}
						String corporationName = ImportUtil.getValue(xssfRow.getCell(0));
						if (!ImportUtil.checkRequired(corporationName)) {
							xssfRow.createCell(0);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(0));
							flag = false;

							/**
							 * 	修改，超过100字符自动截取
							 *	shishouyang
							 *	2015-10-26
							 */
						} /*else if (corporationName.length() > 50) {
							xssfRow.getCell(0);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(0));
							flag = false;
						}*/
						String contactorName = ImportUtil.getValue(xssfRow.getCell(1));
						if (!ImportUtil.checkRequired(contactorName)) {
							xssfRow.createCell(1);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(1));
							flag = false;
							/**
							 * 	联系人长度验证由原来的不超过10变为不超过100
							 * 	再次修改，超过100字符自动截取
							 *	shishouyang
							 *	2015-10-26
							 */
						} /*else if (contactorName.length() > 100) {
							xssfRow.getCell(1);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(1));
							flag = false;
						}*/
						/**
						 * 	取消手机格式验证和电话格式验证
						 *	shishouyang
						 *	2015-10-26
						 */
						/*if (StringUtils.isNotBlank(ImportUtil.getValue(xssfRow.getCell(2))) && !ImportUtil
								.checkMobile(ImportUtil.getValue(xssfRow.getCell(2)))) {
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(2));
							flag = false;
						}
						if (StringUtils.isNotBlank(ImportUtil.getValue(xssfRow.getCell(3))) && !ImportUtil
								.checkPhone(ImportUtil.getValue(xssfRow.getCell(3)))) {
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(3));
							flag = false;
						}*/
						if (StringUtils.isBlank(ImportUtil.getValue(xssfRow.getCell(2))) && StringUtils
								.isBlank(ImportUtil.getValue(xssfRow.getCell(3)))) {
							xssfRow.createCell(2);
							xssfRow.createCell(3);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(2));
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(3));
							flag = false;
						}
						if (!ImportUtil.checkRequired(ImportUtil.getValue(xssfRow.getCell(4)))) {
							xssfRow.createCell(4);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(4));
							flag = false;
						} else if (!ImportUtil.checkWeight(ImportUtil.getValue(xssfRow.getCell(4)))) {
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(4));
							flag = false;
						}
					}

					if (xssfSheet.getLastRowNum() < 3) {
						flag = false;
						errorMsg = "导入文件数据为空,请下载模板重新导入";
					} else if (!flag && xssfSheet.getLastRowNum() >= 3) {
						File targetFile = File.createTempFile("customer-of-import-checked-" + System.currentTimeMillis(), ".xlsx");
						targetFile.deleteOnExit();
						xssfWorkbook.write(new FileOutputStream(targetFile));
						model.addAttribute("fileName", targetFile.getName());
					} else {

						//根据用户角色，判断是否合并
						List<ImportVO> voList = ImportUtil.readXlsx(xssfSheet, "private", UserUtils.getUser().getId());

						int userWeight = 40;
						String userFlag = UserUtils.getUser().getUserType();

						if ("1".equals(userFlag)) {
							userWeight = 90;
						} else if ("2".equals(userFlag)) {
							userWeight = 60;
						}

						//处理导入数据分组信息
						List<PotentialGroup> groupList = potentialGroupService.findList(null);

						for (ImportVO vo : voList) {
							//用户分组
							if (StringUtils.isNotBlank(realGroupId)) {
								vo.setRealGroupId(realGroupId);
								//查询分组信息，检测分组是否删除，同时获取父级分组
								PotentialGroup potentialGroup = getPotentialGroup(groupList, realGroupId);
								if (null != potentialGroup && StringUtils.isNotBlank(potentialGroup.getId())) {
									//顶级分组
									if (potentialGroup.getParentId().equals("0")) {
										vo.setGroup1Id(realGroupId);
										vo.setHasGroup("yes");
									} else { //第二级分组
										PotentialGroup parentGroup = getPotentialGroup(groupList, realGroupId);
										if (parentGroup.getParentId().equals("0")) {
											vo.setGroup1Id(parentGroup.getId());
											vo.setGroup2Id(realGroupId);
											vo.setHasGroup("yes");
										}
									}
								}
							}
						}

						successNum = voList.size();

						long saveBegin = System.currentTimeMillis();

						try {
							mergerNum = importService.save(voList, userWeight, false, "IMPORT");
						} catch (Exception e) {
							flag = false;
							errorMsg = "请检测导入的客户字段是否正确或者联系管理员";
							e.printStackTrace();
						}

						long saveEnd = System.currentTimeMillis();

						logger.info("我的面板>导入添加客户>导入保存合并信息时,处理" + successNum + "条数据,耗时:" + (saveEnd - saveBegin) / 1000 + "秒");
						logger.info("我的面板>导入添加客户>从导入开始到结束,共处理" + successNum + "条数据,共耗时:" + (saveEnd - begin) / 1000 + "秒");
					}
				} else {
					flag = false;
					errorMsg = "导入数据超过1万条,请将数据控制在1万条以内,再重新导入！！！";
				}
			} else {
				flag = false;
				errorMsg = "上传的附件文件不能超过8M！！！";
			}

		} else {
			flag = false;
			errorMsg = "导入文件格式错误,请下载模板重新导入";
		}

		model.addAttribute("successNum", successNum);
		model.addAttribute("mergerNum", mergerNum);
		model.addAttribute("flag", flag);
		model.addAttribute("errorMsg", errorMsg);

		return "modules/mywork/potentialcustomer/potentialCustomerImportResult";
	}


	/**
	 * 获取用户分组信息
	 *
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	private PotentialGroup getPotentialGroup(List<PotentialGroup> groupList, String realGroupId) {
		for (PotentialGroup group : groupList) {
			if (realGroupId.equals(group.getId())) {
				return group;
			}
		}
		return null;
	}


	/**
	 * 下载导入校验结果
	 *
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequiresPermissions("mywork:potentialCustomer:view")
	@RequestMapping(value = "import/checked")
	public ResponseEntity<byte[]> importChecked(String fileName, HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		File templateFile = new File(System.getProperty("java.io.tmpdir") + File.separator + fileName);

		HttpHeaders headers = new HttpHeaders();
		//获取User-Agent
		String agent = request.getHeader("User-Agent");
		if (org.apache.commons.lang3.StringUtils.isNotBlank(agent) && agent.toLowerCase().contains("linux")) {
			//解决Linux系统浏览器乱码
			headers.setContentDispositionFormData("attachment", new String("客户基本信息导入校验结果.xlsx".getBytes("UTF-8"), "ISO8859-1"));
		} else {
			//解决Windows系统浏览器乱码
			headers.setContentDispositionFormData("attachment", new String("客户基本信息导入校验结果.xlsx".getBytes("GBK"), "ISO8859-1"));
		}
		//导出office2010文件，后缀格式.xlsx
		headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(templateFile), headers, HttpStatus.CREATED);
	}

		/*----------------------------导入部分代码 end---------------------------------*/


}